<?php

class Car extends CI_Controller {

    function __construct() {
        parent::__construct();
        $this->load->model("car_model", "project_model");
        $this->load->model("custom_model");
        $this->load->model("admin_user_model");
        $this->load->model("admin_role_model");
        $this->load->model("driver_model");
        $this->load->model("base_model");
        $this->load->model("order_model");

        $this->load->service("admin_manage_service");
        $this->check = $this->admin_manage_service;
        $this->_adminInfo = $this->check->checkAdminLogin();
        #

        $this->projectSet = [
            "url" => [
                "add" => MANAGE_URL . "&c=car&m=add",
                "doAdd" => MANAGE_URL . "&c=car&m=doAdd",
                "edit" => MANAGE_URL . "&c=car&m=edit",
                "doEdit" => MANAGE_URL . "&c=car&m=doEdit",
                "list" => MANAGE_URL . "&c=car&m=lists",
                "doDel" => MANAGE_URL . "&c=car&m=doDel",
            ],
            "file" => [
                "view" => "admin/car",
                "js" => "admin/js/car",
                "cache_ids_name" => "cache_car_ids",
                "power_name" => "car"
            ],
        ];
    }

    /*
     * 添加
     */

    function add() {

        try {
            $this->check->checkPower(array("power" => $this->projectSet["file"]["power_name"] . "_add"));

            $data["navName"] = "添加";

            $data["carType"] = $this->project_model->carType();
            $data["status"] = $this->project_model->status();
            $data["gongyingshang"] = $this->custom_model->getData("where type_id=1 and status_id=1", 1, 0);
            $data["diaodu"] = $this->base_model->getData("select au.* from " . $this->admin_user_model->tableName . " au left join " . $this->admin_role_model->tableName . " ar on au.role_id=ar.id where ar.type_id=1 and au.status_id=1", 1, 0, " order by au.id desc");
            $data["cwjl"] = $this->base_model->getData("select au.* from " . $this->admin_user_model->tableName . " au left join " . $this->admin_role_model->tableName . " ar on au.role_id=ar.id where ar.type_id=2 and au.status_id=1", 1, 0, " order by au.id desc");
            $data["zhujia"] = $this->driver_model->getData("where status_id=1", 1, 0);
            $data["fujia"] = $data["zhujia"];

            $data["doAddUrl"] = $this->projectSet["url"]["doAdd"];

            $this->layout->view($this->projectSet["file"]["view"] . '/add', $data);
        } catch (Exception $e) {
            show_error($msg = $e->getMessage(), $e->getCode() ? $e->getCode() : 200, "系统提示");
        }
    }

    /*
     * 编辑
     */

    function edit() {

        try {

            #权限
            $this->check->checkPower(array("power" => $this->projectSet["file"]["power_name"] . "_view"));

            $data["navName"] = "编辑";

            $id = $this->input->getInt("id", TRUE);
            $editData = $this->project_model->getDataById($id);
            if (empty($editData)) {
                throw new Exception("没有此数据");
            }

            $data["carType"] = $this->project_model->carType();
            $data["status"] = $this->project_model->status();
            $data["gongyingshang"] = $this->custom_model->getData("where type_id=1 and status_id=1", 1, 0);
            $data["diaodu"] = $this->base_model->getData("select au.* from " . $this->admin_user_model->tableName . " au left join " . $this->admin_role_model->tableName . " ar on au.role_id=ar.id where ar.type_id=1", 1, 0, " order by au.id desc");
            $data["cwjl"] = $this->base_model->getData("select au.* from " . $this->admin_user_model->tableName . " au left join " . $this->admin_role_model->tableName . " ar on au.role_id=ar.id where ar.type_id=2", 1, 0, " order by au.id desc");
            $data["zhujia"] = $this->driver_model->getData("where status_id=1", 1, 0);
            $data["fujia"] = $data["zhujia"];

            $data["editData"] = $editData;

            $data["doAddUrl"] = $this->projectSet["url"]["doEdit"];

            $data["backUrl"] = $this->input->getStr("back_url", true, false);

            $this->layout->view($this->projectSet["file"]["view"] . '/add', $data);
        } catch (Exception $e) {
            show_error($msg = $e->getMessage(), $e->getCode() ? $e->getCode() : 200, "系统提示");
        }
    }

    /*
     * 列表
     */

    function lists() {

        try {

            #权限
            $this->check->checkPower(array("power" => $this->projectSet["file"]["power_name"] . "_view"));

            $data["navName"] = "车辆列表";

            $page = $this->input->getInt("page", TRUE);
            if ($page <= 0) {
                $page = 1;
            }
            $pageCount = $this->input->getInt("limit", TRUE);
            if ($pageCount <= 0) {
                $pageCount = 50;
            }
            if ($pageCount >= 200) {
                $pageCount = 200;
            }
            $data["page"] = $page;
            $data["pageCount"] = $pageCount;

            $first = $this->input->getInt("first", true);
            if ($first == 1) {
                $this->session->unset_userdata([$this->projectSet["file"]["cache_ids_name"]]);
            }

            $searchParam = $this->_searchParam();
            $where = $searchParam["where"];
            $pageStrArr = $searchParam["pageStrArr"];
            foreach ($searchParam["data"] as $k => $v) {
                ${$k} = $v;
                $data[$k] = $v;
            }

            $status = $this->project_model->status();
            $data["status"] = $status;

            $carType = $this->project_model->carType();
            $data["carType"] = $carType;

            $sql = " from " . $this->project_model->tableName . " c";
            $sql .= " left join " . $this->custom_model->tableName . " cmp on c.custom_id=cmp.id";
            $sql .= " left join " . $this->driver_model->tableName . " d on c.zhujia_driver_id=d.id";
            $sql .= " left join " . $this->driver_model->tableName . " d2 on c.fujia_driver_id=d2.id";
            $sql .= " left join " . $this->admin_user_model->tableName . " adm on c.diaodu_user_id=adm.id";
            $sql .= " left join " . $this->admin_user_model->tableName . " adm2 on c.cwjl_user_id=adm2.id";

            $listNum = $this->base_model->getDataCount("select c.id" . $sql . " " . $where);
            //$listNum = $this->project_model->getDataCount($where);

            $is_ajax = $this->input->is_ajax_request();
            if ($is_ajax) {

                $dataList = $this->base_model->getData("select c.*,cmp.cmp_bf,d.driver_name as d_driver_name,d.tel as d_tel,d2.driver_name as d2_driver_name,d2.tel as d2_tel,adm.truename as adm_truename,adm2.truename as adm2_truename" . $sql . " " . $where, $page, $pageCount);
                //$dataList = $this->project_model->getData($where, $page, $pageCount);

                foreach ($dataList as $k => $v) {
                    $dataList[$k]["created_at_alias"] = date("Y-m-d H:i:s", $v["created_at"]);
                    $dataList[$k]["updated_at_alias"] = date("Y-m-d H:i:s", $v["updated_at"]);
                    $dataList[$k]["status_name"] = !empty($status[$v["status_id"]]["name"]) ? $status[$v["status_id"]]["name"] : "-";
                    $dataList[$k]["zhujia"] = $v["d_driver_name"] . "/" . $v["d_tel"];
                    $dataList[$k]["fujia"] = $v["d2_driver_name"] . "/" . $v["d2_tel"];
                    $dataList[$k]["car_type_name"] = $carType[$v["car_type"]]["name"];
                }
                $data["dataList"] = $dataList;

                $result = [
                    "code" => 0,
                    "count" => $listNum,
                    "data" => $dataList,
                    "msg" => ""
                ];
                echo jsonEncode($result);
                exit;
            }

            #进行分页
            $pageStr = "";
            if (!empty($pageStrArr)) {
                foreach ($pageStrArr as $k => $v) {
                    $pageStr .= "&" . $k . "=" . $v;
                }
            }
            $data['base_url'] = $this->projectSet["url"]["list"] . $pageStr;

            $data["listNum"] = $listNum;

            $this->layout->view($this->projectSet["file"]["view"] . '/list', $data);
        } catch (Exception $e) {
            show_error($msg = $e->getMessage(), $e->getCode() ? $e->getCode() : 200, "系统提示");
        }
    }

    /*
     * 
     */

    function doAdd() {

        #权限

        $flag = 0;
        $msg = "操作失败";

        try {

            $this->check->checkPower(array("power" => $this->projectSet["file"]["power_name"] . "_add"));

            $needField = $this->project_model->needField();
            $fieldValue = $this->common->checkField($needField);

            $fieldValue["car_number"] = strtoupper($fieldValue["car_number"]);
            $car = $this->project_model->getData("where car_number='" . $fieldValue["car_number"] . "'", 1, 1, "");
            if (!empty($car)) {
                throw new Exception("此车辆已经存在");
            }


            $uData = array_merge($fieldValue, [
                "created_at" => time(),
                "updated_at" => time(),
            ]);
            $insert_id = $this->project_model->addData($uData);

            $flag = 1;
            $msg = "操作成功";
        } catch (Exception $e) {
            $msg = $e->getMessage();
        }

        $outArr = array("flag" => $flag, "msg" => $msg);
        echo jsonEncode($outArr);
    }

    /*
     * 
     */

    function doEdit() {

        $flag = 0;
        $msg = "操作失败";

        try {

            $this->check->checkPower(array("power" => $this->projectSet["file"]["power_name"] . "_edit", "ajax" => 1));

            $needField = $this->project_model->needField();

            $fieldValue = $this->common->checkField($needField);

            $id = $this->input->postInt("id", TRUE);

            $oldData = $this->project_model->getDataById($id);
            if (empty($oldData)) {
                throw new Exception("数据不存在");
            }

            $fieldValue["car_number"] = strtoupper($fieldValue["car_number"]);
            $car = $this->project_model->getData("where id!=" . $id . " and car_number='" . $fieldValue["car_number"] . "'", 1, 1, "");
            if (!empty($car)) {
                throw new Exception("此车辆已经存在");
            }

            $uData = array_merge($fieldValue, [
                "updated_at" => time(),
            ]);

            $data = [
                "fieldArr" => $uData,
                "whereArr" => [
                    "id" => $id,
                ],
            ];
            $this->project_model->updateData($data);

            $flag = 1;
            $msg = "操作成功";
        } catch (Exception $e) {
            $msg = $e->getMessage();
        }

        $outArr = array("flag" => $flag, "msg" => $msg);
        echo jsonEncode($outArr);
    }

    /*
     * 删除记录
     */

    public function doDel() {

        $flag = 0;
        $msg = "操作失败";

        try {

            $this->check->checkPower(array("power" => $this->projectSet["file"]["power_name"] . "_del", "ajax" => 1));

            $id = $this->input->postInt("id", TRUE);
            if ($id <= 0) {
                throw new Exception("数据id为空");
            }

            $oldData = $this->project_model->getDataById($id);
            if (empty($oldData)) {
                throw new Exception("数据不存在");
            }

            $order = $this->order_model->getData("where car_id=" . $id, 1, 1, "");
            if (!empty($order)) {
                throw new Exception("该车辆已存在订单，不可删除");
            }

            $paramArr = array(
                "whereArr" => array(
                    "id" => $id
                ),
            );
            $result = $this->project_model->delData($paramArr);

            $flag = 1;
            $msg = "操作成功";
        } catch (Exception $e) {
            $msg = $e->getMessage();
        }
        $outArr = array("flag" => $flag, "msg" => $msg);
        echo jsonEncode($outArr);
    }

    public function _searchParam() {

        $pageStrArr = array();
        $where = "where 1";

        //状态
        $status_id = (isset($_GET["status_id"]) || isset($_POST["status_id"])) ? $this->input->getPostInt("status_id", TRUE) : -1;
        if ($status_id > -1) {
            $pageStrArr["status_id"] = $status_id;
            $where .= " AND c.status_id = " . $status_id;
        }
        $data["status_id"] = $status_id;

        $car_number = $this->input->getPostStr("car_number", TRUE);
        if ($car_number != "") {
            $pageStrArr["car_number"] = $car_number;
            $where .= " AND c.car_number like '%" . $car_number . "%'";
        }
        $data["car_number"] = $car_number;

        $zibianhao = $this->input->getPostStr("zibianhao", TRUE);
        if ($zibianhao != "") {
            $pageStrArr["zibianhao"] = $zibianhao;
            $where .= " AND c.zibianhao like '%" . $zibianhao . "%'";
        }
        $data["zibianhao"] = $zibianhao;

        return [
            "data" => $data,
            "pageStrArr" => $pageStrArr,
            "where" => $where,
        ];
    }

    public function doSelectIds() {

        #权限
        //$this->check->checkPower(array("power" => "idcard_edit", "ajax" => 1));

        $flag = 0;
        $msg = "操作失败";
        $id_arr = $this->input->postStr("ids", TRUE, false);

        try {
            $sessionData = [
                $this->projectSet["file"]["cache_ids_name"] => $id_arr,
            ];
            $this->session->set_userdata($sessionData);

            $flag = 1;
            $msg = "操作成功";
            //事务结束
        } catch (Exception $e) {
            $msg = $e->getMessage();
        }
        $outArr = array("flag" => $flag, "msg" => $msg);
        echo jsonEncode($outArr);
    }

    public function getCar() {

        $result = [];
        $custom_id = $this->input->getInt("custom_id", TRUE);

        if ($custom_id > 0) {

            $sql = " from " . $this->project_model->tableName . " c";
            $sql .= " left join " . $this->custom_model->tableName . " cmp on c.custom_id=cmp.id";
            $sql .= " left join " . $this->driver_model->tableName . " d on c.zhujia_driver_id=d.id";
            $sql .= " left join " . $this->admin_user_model->tableName . " adm on c.diaodu_user_id=adm.id";

            $where = " where 1";
            if ($custom_id > 0) {
                $where .= " and c.custom_id=" . $custom_id;
            }
            if ($this->_adminInfo["role"]["type_id"] == 1) {//调度调自己的车辆
                $where .= " and c.diaodu_user_id=" . $this->_adminInfo["id"];
            }
            $list = $this->base_model->getData("select c.*,d.driver_name as d_driver_name,d.tel as d_tel,adm.truename as adm_truename" . $sql . $where, 1, 0);
            $result = $list;
        }
        echo jsonEncode($result);
    }

}
